#define _CRT_SECURE_NO_WARNINGS 1
#include "List.h"
ListNode* BuyNode(typedata x) {
	ListNode* node = (ListNode*)malloc(sizeof(ListNode));
	node->data = x;
	node->prev = NULL;
	node->next = NULL;
	return node;
}
void ListInit(ListNode** pphead) {
	assert(pphead);
	*pphead = BuyNode(0);
	(*pphead)->prev = *pphead;
	(*pphead)->next = *pphead;
}
void ListPrint(ListNode* phead) {
	assert(phead);
	ListNode* cur = phead->next;
	while (cur != phead) {
		printf("%d ", cur->data);
		cur = cur->next;
	}
	printf("\n");
}
void ListClear(ListNode* phead) {
	assert(phead);
	ListNode* cur = phead;
	while (cur != phead) {
		ListNode* next = cur->next;
		free(cur);
		cur = next;
	}
	phead->next = phead;
	phead->prev = phead;
}
void ListDestroy(ListNode* phead) {
	ListClear(phead);
	free(phead);
}

ListNode* ListFind(ListNode* phead, typedata x) {
	assert(phead);
	ListNode* cur = phead->next;
	while (cur != phead) {
		if (cur->data == x) {
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void ListPushBack(ListNode* phead, typedata x) {
	ListInsert(phead, x);
}
void ListPopBack(ListNode* phead) {
	ListDelete(phead->prev);
}
void ListPushFront(ListNode* phead, typedata x) {
	ListInsert(phead->next, x);
}
void ListPopFront(ListNode* phead) {
	ListDelete(phead->next);
}
void ListInsert(ListNode* pos, typedata x) {
	assert(pos);
	ListNode* prev = pos->prev;
	ListNode* newNode = BuyNode(x);
	prev->next = newNode;
	newNode->prev = prev;
	newNode->next = pos;
	pos->prev = newNode;
}
void ListDelete(ListNode* pos) {
	assert(pos);
	ListNode* prev = pos->prev;
	ListNode* next = pos->next;
	prev->next = next;
	next->prev = prev;
	free(pos);
}
